import React from 'react';
import { Form, Input, Button, Row, Col, Checkbox, message, Icon } from 'antd';
import { changeMobileSendSms, changeMobileValidCode, changeMobile } from '../../api';
import './index.less'
import { Dialog } from 'components'
const FormItem = Form.Item;

class UpdateMobilePhoneModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      validCodeImg: '',
      mobilePhoneValidCodeFlag: false,
      seconds: '获取验证码',
    };
  }

  componentDidMount() {
    this.changeMobileValidCode();
  }
  // 获取验证码
  changeMobileValidCode = () => {
    changeMobileValidCode((res) => {
      this.setState({
        validCodeImg: res.data,
      });
    });
  }
  // 确认
  handleSubmit = (e) => {
    e.preventDefault();
    const { form, handleConfirm } = this.props;
    form.validateFields((err, values) => {
      if (!err) {
        const { validCode, mobileCode, mobilePhone } = values;
        const postData = { validCode, mobilePhone, mobileCode };
        changeMobile(postData, () => {
          Dialog({
            message: '设置成功'
          })
          handleConfirm();
        }, (err) => {
          if(err.code == 6){
            form.setFields({
              validCode: {
                value: validCode,
                errors: [new Error(err.msg)],
              }
            })
          }else if(err.code == 8){
            form.setFields({
              mobileCode: {
                value: mobileCode,
                errors: [new Error(err.msg)],
              }
            })
          }
          this.changeMobileValidCode();
        });
      }
    });
  }
  handleClose = () => {
    const { handleCloseModal } = this.props;
    handleCloseModal();
  }

  // 自定义手机号校验
  validatePhone = (rule, value, callback) => {
    if (value && !/^1([38]\d|5[0-35-9]|7[3678])\d{8}$/.test(value)) {
      callback('请输入正确的11位手机号');
    } else {
      callback();
    }
  }
  // 点击获取手机验证码
  clickMobilePhoneValidCode = () => {
    const { form } = this.props;
    const mobilePhone = form.getFieldValue('mobilePhone');
    if(mobilePhone == undefined){
      form.validateFields(['mobilePhone'], { force: true });
    }else{
      const postData = { mobilePhone };
      changeMobileSendSms(postData, () => {
        this.startCountDown();
      }, (err) => {
        form.setFields({
          mobilePhone: {
            value: mobilePhone,
            errors: [new Error(err.msg)],
          }
        })
        this.changeMobileValidCode();
        // this.startCountDown();
      });
    }
  }
  // 开启倒计时
  startCountDown = () => {
    // const form = this.props.form;
    // const mobilePhone = form.getFieldValue('mobilePhone');
    let timer = null;
    this.setState({
      seconds: 120,
      mobilePhoneValidCodeFlag: true,
    }, () => {
      timer = setInterval(() => {
        if (this.state.seconds === 0) {
          this.setState({
            seconds: '重新获取',
            mobilePhoneValidCodeFlag: false,
          });
          clearInterval(timer);
          timer = null;
          return;
        }
        this.setState(prevState => ({ seconds: prevState.seconds - 1 }));
      }, 1000);
    });
  }
  render() {
    const { validCodeImg, mobilePhoneValidCodeFlag, seconds } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="image-code-form">
        <span className="image-close" onClick={this.handleClose}></span>
        <p className="image-title">更换手机号码</p>
        <Form onSubmit={this.handleSubmit} onKeyDown={(e) => { if (e.keyCode == 13) { e.preventDefault(); } }}>
          <FormItem style={{ marginBottom: 0, height: 64 }}>
            {getFieldDecorator('mobilePhone', {
              rules: [
                { required: true, message: '手机号不能为空' },
                { validator: this.validatePhone },
              ],
            })(<p><Input 
              size="large"
              placeholder="请输入11位有效手机号码" 
              autoComplete="off" 
              prefix={<Icon type="mobile" style={{ color: '#bbb', fontSize: 18 }} />}
            /></p>)}
          </FormItem>
          <FormItem style={{ marginBottom: 0, height: 64 }}>
            <div className="con-left">
            {getFieldDecorator('validCode', {
                  rules: [
                    { required: true, message: '请输入正确的图形验证码' },
                  ],
                })(<p><Input 
                  size="large"
                  prefix={<Icon type="safety" style={{ color: '#bbb', fontSize: 18 }} />}
                  placeholder="请输入图形验证码" autoComplete="off" /></p>)}
            </div>
            <div className="con-right" onClick={this.changeMobileValidCode}>
              <img style={{ width: 100, height: 40, cursor: 'pointer', verticalAlign: 'top' }} src={validCodeImg} alt="" />
            </div>
          </FormItem>
          <FormItem style={{ marginBottom: 0, height: 64 }}>
            <div className="con-left">
              {getFieldDecorator('mobileCode', {
                rules: [
                  { required: true, message: '手机验证码不能为空' },
                ],
              })(<p><Input 
                size="large"
                prefix={<Icon type="safety" style={{ color: '#bbb', fontSize: 18 }} />}
                placeholder="请输入6位手机验证码" autoComplete="off" /></p>)}
            </div>
            <div className="con-right">
              <Button
                style={{ width: 100, height: 40, borderRadius: 2 }}
                type="primary"
                disabled={mobilePhoneValidCodeFlag}
                onClick={this.clickMobilePhoneValidCode}
              >{seconds}
              </Button>
            </div>
          </FormItem>
          <Button type="primary" htmlType="submit" className="login-form-button">确认</Button>
        </Form>
      </div>
    );
  }
}

const WrapUpdateMobilePhoneModal = Form.create()(UpdateMobilePhoneModal);

export default WrapUpdateMobilePhoneModal